<?php
declare (strict_types = 1);

namespace app\common\validate;

use think\Validate;
use app\index\model\Comment as CommentModel;
use app\common\model\content\Article;

class Comment extends Validate
{
    private $articleModel = null; //缓存文章模型
    /**
     * 定义验证规则
     * 格式：'字段名'	=>	['规则1','规则2'...]
     *
     * @var array
     */	
	protected $rule = [
        'comment'   =>'require|max:512',
        'parent_id' =>'integer|checkParentExist|checkLimit',
        'article_id'=>'require|checkArticleExist|checkDisallow',
    ];
    
    /**
     * 定义错误信息
     * 格式：'字段名.规则名'	=>	'错误信息'
     *
     * @var array
     */	
    protected $message = [
        'comment.require' => '评论不能为空.',
        'comment.max' => '评论长度不能超过512.',
        'parent_id.integer' => '指定评论错误.',
        'parent_id.checkParentExist' => '指定评论不存在.',
        'parent_id.checkLimit' => '回复已达上限.',
        'article_id.require' => '文章信息不能为空.',
        'article_id.checkArticleExist' => '文章不存在.',
        'article_id.checkDisallow' => '文章禁止评论.',


    ];

    // 检测父id是否正确
    protected function checkParentExist($value, $rule, $data=[])
    {
        if ((int)$value >= 1)
            return (bool) CommentModel::where(['id'=>$value])->count();
        return true;
    }
    // 检测文章是否存在
    protected function checkArticleExist($value, $rule, $data=[])
    {
        $articleModel = Article::find($value);
        if ($articleModel)
            $this->articleModel = $articleModel;

        return (bool) $articleModel;
    }
    //检测评论的回复个数是否达到上限(一个平评论只允许多少个回复)
    protected function checkLimit($value, $rule, $data=[]){
        if ((int)$value >= 1)
            return (bool) !(CommentModel::where([
                'parent_id'=>$value
            ])->count() >= CommentModel::REPLIES_LIMIT);
        return true;
    }
    //检测文章是否允许评论
    protected function checkDisallow($value, $rule, $data=[]){
        if (!$this->articleModel) return false;
        return !$this->articleModel->disallow;
    }
}
